package ve.lm.hrms_cy.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import ve.lm.hrms_cy.Entity.*;
import ve.lm.hrms_cy.Entity.Request.DepartmentQueryRequest;
import ve.lm.hrms_cy.Entity.Request.EmployeeQueryRequest;
import ve.lm.hrms_cy.Entity.Request.UserQueryRequest;
import ve.lm.hrms_cy.Entity.Response.ResponseEntityCY;
import ve.lm.hrms_cy.Mapper.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class SystemManagerService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    EmployeeMapper employeeMapper;

    @Autowired
    DepartmentMapper departmentMapper;



    public IPage<User> findUserByPage(UserQueryRequest queryRequest) {
        Integer current = queryRequest.getCurrent() != null ? queryRequest.getCurrent() : 1;
        Integer size = queryRequest.getSize() != null ? queryRequest.getSize() : 10;

        Page<User> page = new Page<>(current, size);

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();

        // ID 精确查询
        if (queryRequest.getId() != null) {
            queryWrapper.eq(User::getId, queryRequest.getId());
        }

        // keyword 模糊查询 name 或 email
        if (queryRequest.getKeyword() != null && !queryRequest.getKeyword().trim().isEmpty()) {
            queryWrapper.and(wrapper ->
                    wrapper.like(User::getName, queryRequest.getKeyword())
                            .or()
                            .like(User::getEmail, queryRequest.getKeyword())
            );
        }

        // 注册时间范围查询
        if (queryRequest.getStartTime() != null) {
            queryWrapper.ge(User::getRegisterTime, queryRequest.getStartTime());
        }
        if (queryRequest.getEndTime() != null) {
            queryWrapper.le(User::getRegisterTime, queryRequest.getEndTime());
        }

        return userMapper.selectPage(page, queryWrapper);
    }


    @Transactional
    public ResponseEntityCY<Boolean> addUser(User userRequest) {
        String name = userRequest.getName();
        String email = userRequest.getEmail();

        // 1. 查询 name 或 email 冲突，且状态不是“注销”
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.and(wrapper ->
                wrapper.eq(User::getName, name)
                        .or()
                        .eq(User::getEmail, email)
        ).ne(User::getStatus, "注销");

        List<User> existing = userMapper.selectList(queryWrapper);
        if (!existing.isEmpty()) {
            return new ResponseEntityCY<>("409", false, false, "用户名或邮箱已存在，且未注销！");
        }

        // 2. 获取当前最大 ID（可能为空）
        Long maxId = Optional.ofNullable(
                userMapper.selectList(null)
                        .stream()
                        .map(User::getId)
                        .max(Long::compareTo)
                        .orElse(0L)
        ).orElse(0L);

        Long newId = maxId + 1;

        // 3. 构造新用户对象（包括 registerTime）
        User newUser = new User(
                userRequest.getName(),
                userRequest.getEmail(),
                userRequest.getPermission(),
                userRequest.getStatus(),
                userRequest.getPassword()
        );
        newUser.setId(newId);
        newUser.setRegisterTime(LocalDateTime.now());

        // 4. 添加进数据库
        int rows = userMapper.insert(newUser);
        if (rows > 0) {
            return new ResponseEntityCY<>("200", true, true, "用户添加成功！");
        } else {
            return new ResponseEntityCY<>("500", false, false, "添加用户失败！");
        }
    }


    public ResponseEntityCY<Boolean> updateUser(User updatedUser) {
        // 使用 LambdaQueryWrapper 根据 name 和 email 查找用户


        User existingUser = userMapper.selectById(updatedUser.getId());

        if (existingUser == null) {
            return new ResponseEntityCY<>("400", false, false, "未能查找到更新用户！");
        }

        // 执行更新
        int rows = userMapper.updateById(updatedUser);
        if(rows>0)
         return  new ResponseEntityCY<>("200",true,true,"成功更新用户！");

        return  new ResponseEntityCY<>("500",false,false,"在使用userMapper更新用户时出现错误！");
    }

    public ResponseEntityCY<Boolean> deleteOrRecoverUser(Long id ,Boolean isDelete){

        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getId, id);

        User findUser=userMapper.selectOne(lambdaQueryWrapper);

        if(findUser==null)
            return new ResponseEntityCY<>("400",false,false,"未能发现用户！");




        if(isDelete&&findUser.getStatus().equals("注销"))
            return new ResponseEntityCY<>("400",false,true,"该用户已注销！");

        if(!isDelete&&findUser.getStatus().equals("正常"))
            return new ResponseEntityCY<>("400",false,true,"该用户已恢复！");


        User updateUser = new User(findUser.getName(),findUser.getEmail(),findUser.getPermission(),"注销",findUser.getPassword());

        if(!isDelete)
            updateUser.setStatus("正常");


        updateUser.setId(id);
        updateUser.setRegisterTime(findUser.getRegisterTime());

        int row = userMapper.updateById(updateUser);

        if(row >0 &&isDelete)
            return new ResponseEntityCY<>("200",true,true,"成功注销用户！");
        else if(row >0)
            return new ResponseEntityCY<>("200",true,true,"成功恢复用户！");
        else
            return new ResponseEntityCY<>("114514",false,false,"操作可行通过的情况下的未知错误！");
    }





    public ResponseEntityCY<Boolean> addEmployee(Employee employee){

        String name= employee.getName();
        String phoneNumber=employee.getPhoneNumber();

        LambdaQueryWrapper<Employee> lambdaQueryWrapper =new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Employee::getName,name).or().eq(Employee::getPhoneNumber, phoneNumber);

        Employee findEmployee = employeeMapper.selectOne(lambdaQueryWrapper);

        if(findEmployee!=null){

            return new ResponseEntityCY<>("409",false,false,"已经有该职工了！");

        }


        Long maxId = Optional.ofNullable(
                employeeMapper.selectList(null)
                        .stream()
                        .map(Employee::getId)
                        .max(Long::compareTo)
                        .orElse(0L)
        ).orElse(0L);

        employee.setId(maxId+1);

        if(employeeMapper.insert(employee)>0)
            return new ResponseEntityCY<>("200",true,true,"职工信息录入成功！");

        return  new ResponseEntityCY<>("500",false,false,"在职工信息录入可行的情况下出现未知错误！");


    }

    public ResponseEntityCY<IPage<Employee>>  findEmployeeByPage(EmployeeQueryRequest employeeQueryRequest){


        Integer current = employeeQueryRequest.getCurrent() != null ? employeeQueryRequest.getCurrent() : 1;
        Integer size = employeeQueryRequest.getSize() != null ? employeeQueryRequest.getSize() : 10;

        Page<Employee> page = new Page<>(current, size);

        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();

        // ID 精确查询
        if (employeeQueryRequest.getId() != null) {
            queryWrapper.eq(Employee::getId, employeeQueryRequest.getId());
        }

        // keyword 模糊查询 name 或 email
        if (employeeQueryRequest.getKeyword() != null && !employeeQueryRequest.getKeyword().trim().isEmpty()) {
            queryWrapper.and(wrapper ->
                    wrapper.like(Employee::getName, employeeQueryRequest.getKeyword())
                            .or()
                            .like(Employee::getPosition, employeeQueryRequest.getKeyword())
                            .or().like(Employee::getDepartment, employeeQueryRequest.getKeyword())
            );
        }
        if(employeeQueryRequest.getGender()!=null)
            queryWrapper.like(Employee::getGender,employeeQueryRequest.getGender());

//        System.out.println(employeeQueryRequest.getLeaveStart());

        // 注册时间范围查询
        if (employeeQueryRequest.getComeStart() != null) {
            queryWrapper.ge(Employee::getComeOfficeTime, employeeQueryRequest.getComeStart());
        }
        if(employeeQueryRequest.getComeEnd()!=null){
            queryWrapper.le(Employee::getComeOfficeTime, employeeQueryRequest.getComeEnd());
        }
        if (employeeQueryRequest.getLeaveStart() != null) {
//            System.out.println("哈哈");
//            queryWrapper.isNotNull(Employee::getLeaveOfficeTime);
            queryWrapper.ge(Employee ::getLeaveOfficeTime, employeeQueryRequest.getLeaveStart());
        }
        if (employeeQueryRequest.getLeaveEnd() != null) {
            queryWrapper.le(Employee ::getLeaveOfficeTime, employeeQueryRequest.getLeaveEnd());
        }




        return new ResponseEntityCY<> ("200",true, employeeMapper.selectPage(page ,queryWrapper),"成功查询职工信息！");

    }

    public ResponseEntityCY<Boolean> updateEmployee(Employee employee){

        Employee findEmployee = employeeMapper.selectById(employee.getId());


//        System.out.println(employee.getPosition());

        if(findEmployee==null)
            return new ResponseEntityCY<>("400",false,false,"未发现职工信息！");

        Employee updateEmployee = new Employee(employee.getName(), employee.getGender(), employee.getPosition(), employee.getDepartment(), employee.getComeOfficeTime() ,employee.getLeaveOfficeTime() , employee.getStatus(), employee.getPhoneNumber());

        updateEmployee.setId(employee.getId());

        int row =employeeMapper.updateById(updateEmployee);

        if(row>0)
            return new ResponseEntityCY<>("200",true,true,"成功更新职工信息！");

        return new ResponseEntityCY<>("500",false,false,"在更新职工可行的情况下出现未知错误！");

    }


    public ResponseEntityCY<Boolean> addDepartment(Department department){

        LambdaQueryWrapper<Department> lambdaQueryWrapper =new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Department::getName , department.getName());

        Department findDepartment = departmentMapper.selectOne(lambdaQueryWrapper);

        if(findDepartment!=null)
            return new ResponseEntityCY<>("409",false,false,"该部门已注册！");

        Long maxId = Optional.ofNullable(
                departmentMapper.selectList(null)
                        .stream()
                        .map(Department::getId)
                        .max(Long::compareTo)
                        .orElse(0L)
        ).orElse(0L);


        department.setId(maxId+1);

        department.setBuildTime(LocalDateTime.now());

        int row = departmentMapper.insert(department);

        if(row>0)
            return new ResponseEntityCY<>("200",true,true,"部门注册成功！");

        return new ResponseEntityCY<>("500" ,false,false,"在注册部门可行的情况下出现未知错误！");

    }
    public ResponseEntityCY<IPage<Department>> findDepartmentByPage(DepartmentQueryRequest departmentQueryRequest){

        LambdaQueryWrapper<Department> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        Page<Department> page = new Page<>(departmentQueryRequest.getCurrent(),departmentQueryRequest.getSize());

        if(departmentQueryRequest.getId()!=null)
              lambdaQueryWrapper.eq(Department::getId , departmentQueryRequest.getId());

        if(departmentQueryRequest.getName()!=null)
            lambdaQueryWrapper.like(Department::getName , departmentQueryRequest.getName());

        if(departmentQueryRequest.getStartTime()!=null)
            lambdaQueryWrapper.ge(Department::getBuildTime , departmentQueryRequest.getStartTime());

        if(departmentQueryRequest.getEndTime()!=null)
            lambdaQueryWrapper.le(Department::getBuildTime , departmentQueryRequest.getEndTime());


        return new ResponseEntityCY<>("200",true,departmentMapper.selectPage(page,lambdaQueryWrapper),"成功查询部门！");


    }
    public ResponseEntityCY<Boolean> updateDepartment(Department department){

         Department findDepartment = departmentMapper.selectById(department.getId());

         System.out.println("总裁Id:" +department.getPresidentId());

         if(findDepartment==null)
             return new ResponseEntityCY<>("400",false,true,"未能发现该部门！");

       if(department.getPresidentId()==null)
           department.setPresidentId(-1L);



         int row = departmentMapper.updateById(department);

         if(row>0)
             return new ResponseEntityCY<>("200",true,true,"成功更新部门信息！");

         return new ResponseEntityCY<>("500",true,true,"在更新部门可行的情况下出现未知错误！");

    }
    public ResponseEntityCY<Boolean> deleteOrRecoverDepartment(Long id , Boolean isDelete){

        Department findDepartment = departmentMapper.selectById(id);

        if(findDepartment==null)
            return new ResponseEntityCY<>("400",false,false,"未能发现该部门！");

        if(findDepartment.getStatus().equals("注销")&&isDelete)
            return new ResponseEntityCY<>("400",false,true,"该部门已经注销！");

        if(findDepartment.getStatus().equals("正常")&&!isDelete)
            return new ResponseEntityCY<>("400",false,true,"该部门已经恢复！");

        findDepartment.setStatus(isDelete?"注销":"正常");

        int row = departmentMapper.updateById(findDepartment);

        if(row>0 &&isDelete)
            return new ResponseEntityCY<>("200",true,true,"成功注销该部门！");
        else if(row>0)
            return new ResponseEntityCY<>("200",true,true,"成功恢复该部门！");
        else
            return new ResponseEntityCY<>("500",false,false,"在操作可行的情况下出现未知错误！");

    }

    public ResponseEntityCY<User> findUserById(Long id){

        User findUser = userMapper.selectById(id);

        if(findUser==null)
            return new ResponseEntityCY<>("400",false,null,"未能查询到用户信息！ ");

        return new ResponseEntityCY<>("200",true,findUser,"成功查询用户信息！");

    }

    public ResponseEntityCY<Boolean> updatePassword(Long id,String oldPassword ,String newPassword){

        User findUser =userMapper.selectById(id);

        if(findUser==null)
            return new ResponseEntityCY<>("400",false,null,"未能查询到用户信息！ ");

        if(!findUser.getPassword().equals(oldPassword))
            return new ResponseEntityCY<>("400",false,true,"密码错误！");


        findUser.setPassword(newPassword);

        int row =userMapper.updateById(findUser);

        if(row>0)
            return new ResponseEntityCY<>("200",true,true,"修改密码成功！");


        return new ResponseEntityCY<>("500",true,true,"在操作可行的情况下出现未知错误！");

    }





}
